
<template>
    <BasicLayout>
        <template #wrapper>
            <el-card class="box-card">
                <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
                    <!-- <el-form-item label="场景" prop="sceneCode">
            <el-select v-model="queryParams.sceneCode" placeholder="来源场景值" clearable size="small">
              <el-option
                v-for="dict in sceneCodeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="用户等级" prop="userLevel">
            <el-select v-model="queryParams.userLevel" placeholder="兑换的用户等级" clearable size="small">
              <el-option
                v-for="dict in userLevelOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item> -->
                    <!-- <el-form-item label="使用时间" prop="useAt">
                        <el-date-picker v-model="queryParams.useAt" value-format="yyyy-MM-dd" type="daterange"
                            :picker-options="pickerOptions" range-separator="至" start-placeholder="开始日期"
                            end-placeholder="结束日期" size="small" align="right" @keyup.enter.native="handleQuery">
                        </el-date-picker>
                    </el-form-item> -->
                    <!-- <el-form-item label="状态" prop="useStatus">
                        <el-select v-model="queryParams.useStatus" placeholder="激活券使用状态" clearable size="small">
                            <el-option v-for="dict in useStatusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                                :value="dict.dictValue" />
                        </el-select>
                    </el-form-item> -->

                    <!-- <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item> -->
                </el-form>

                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button v-permisaction="['activationcoupon:user:remove']" type="danger" icon="el-icon-delete"
                            size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
                    </el-col>
                </el-row>

                <el-table v-loading="loading" :data="activationcouponuserList">
                    <!-- <el-table-column type="selection" width="55" align="center" /> -->
                    <el-table-column label="下单用户" align="center" prop="userId" :show-overflow-tooltip="true" />

                    <el-table-column label="服务" width="200px" align="center" prop="remark"
                        :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <div v-for="item in scope.row.itemList" class="row ali_cen" :key="item.serviceId">
                                <el-image style="width: 30px; height:30px;margin-right:10px" :src="item.cover">
                                </el-image>
                                <div style="margin-right:10px">{{item.title}}*{{item.num}}</div>
                                <div>￥{{item.price}}</div>
                            </div>
                        </template>
                    </el-table-column>

                    <el-table-column label="订单总价" align="center" prop="totalPrice" :show-overflow-tooltip="true" />

                    <el-table-column label="抵扣金额" align="center" prop="deductionPrice" :show-overflow-tooltip="true" />
                    <el-table-column label="实际支付金额" align="center" prop="payPrice" :show-overflow-tooltip="true" />
                    <el-table-column label="订单号" align="center" prop="orderNumber" :show-overflow-tooltip="true" />
                    <el-table-column label="交易号" align="center" prop="tradeSn" :show-overflow-tooltip="true" />
                    <el-table-column label="订单状态" align="center" prop="tradeStatus" :formatter="tradeStatusFormat"
                        width="100">
                        <template slot-scope="scope">
                            {{ tradeStatusFormat(scope.row) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="下单时间" align="center" prop="createdAt" :show-overflow-tooltip="true" />
                    <el-table-column label="支付时间" align="center" prop="payAt" :show-overflow-tooltip="true" />

                    <el-table-column label="管理员备注" align="center" prop="remark" :show-overflow-tooltip="true" />

                    <el-table-column label="操作" align="center" width="150px" class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <!-- <el-button v-permisaction="['edu:order:edit']" size="mini" type="text" icon="el-icon-edit"
                                @click="handleUpdate(scope.row)">修改
                            </el-button> -->
                            <el-button v-permisaction="['edu:order:edit']" size="mini" type="text" icon="el-icon-edit"
                                @click="handlePut(scope.row)">核销
                            </el-button>
                            <el-button v-permisaction="['edu:order:remove']" size="mini" type="text"
                                icon="el-icon-delete" @click="handleDelete(scope.row)">取消
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageIndex"
                    :limit.sync="queryParams.pageSize" @pagination="getList" />

                <!-- 添加或修改对话框 -->

            </el-card>
        </template>
    </BasicLayout>
</template>

<script>
import {
    addEduOrder,
    delEduOrder,
    getEduOrder,
    listEduOrder,
    updateEduOrder,
} from "@/api/edu/finance/order";
import {
    listgeneralUser,
    getgeneralUser,
    delgeneralUser,
    addgeneralUser,
    updategeneralUser,
} from "@/api/generaluser";
import { serviceList, storeList, postOrder, putOrder, putUseOrder } from '@/api/user';
export default {
    name: "Config",
    props: {
        userId: {
            type: Number,
            default: () => {
                return 0;
            },
        },
        phone: {
            type: String,
            default: () => {
                return "";
            },
        },

    },
    data () {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            isEdit: false,
            // 类型数据字典
            typeOptions: [],
            activationcouponuserList: [],
            sceneCodeOptions: [],
            userLevelOptions: [],
            useStatusOptions: [],
            couponStatusOptions: [],
            // 查询参数
            queryParams: {
                pageIndex: 1,
                pageSize: 10,
                phone: this.phone,
                userId: this.userId,
                sceneCode: undefined,
                userLevel: undefined,
                useAt: undefined,
                useStatus: undefined,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                phone: [
                    { required: true, message: "激活券来源不能为空", trigger: "blur" },
                ],
                userId: [
                    { required: true, message: "用户id不能为空", trigger: "blur" },
                ],
                sceneCode: [
                    { required: true, message: "来源场景值不能为空", trigger: "blur" },
                ],
                userLevel: [
                    {
                        required: true,
                        message: "兑换的用户等级不能为空",
                        trigger: "blur",
                    },
                ],
                useAt: [
                    { required: true, message: "使用时间不能为空", trigger: "blur" },
                ],
                useStatus: [
                    {
                        required: true,
                        message: "状态（1：未使用，2：已使用）不能为空",
                        trigger: "blur",
                    },
                ],
            },
        };
    },
    created () {
        this.getList();
        this.couponStatusOptions = this.$store.getters.parameter.sys_bool;
        this.useStatusOptions = this.$store.getters.parameter.activation_coupon_use_status;
        this.userLevelOptions = this.$store.getters.parameter.general_user_level;
        this.vipDurationOptions = this.$store.getters.parameter.sys_sku_duration;
        this.sceneCodeOptions = this.$store.getters.parameter.mp_scene;
        this.getDicts("edu_trade_status").then((response) => {
            this.tradeStatusOptions = response.data;
        });
    },
    watch: {
        //监听子控件内容的改动,发送给父级组件
        userId: {
            handler (newValue, oldValue) {
                this.queryParams.userId = this.userId;
                this.queryParams.phone = this.phone
                this.getList();
            },
            deep: true,
        },

        phone: {
            handler (newValue, oldValue) {
                this.queryParams.userId = this.userId;
                this.queryParams.phone = this.phone
                this.getList();
            },
            deep: true,
        },
    },
    methods: {
        tradeStatusFormat (row) {
            return this.selectDictLabel(this.tradeStatusOptions, row.tradeStatus);
        },
        /** 查询参数列表 */
        getList () {
            this.loading = true;
            listEduOrder(this.addDateRange(this.queryParams, this.dateRange)).then(
                (response) => {
                    this.activationcouponuserList = response.data.list;
                    console.log(this.activationcouponuserList)
                    this.total = response.data.count;
                    this.loading = false;
                }
            );
        },
        // 取消按钮
        cancel () {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset () {
            this.form = {
                couponUserId: undefined,
                phone: undefined,
                couponTitle: undefined,
                userId: undefined,
                sceneCode: undefined,
                vipDuration: undefined,
                userLevel: undefined,
                mark: undefined,
                weigh: undefined,
                useAt: undefined,
                useStatus: undefined,
            };
            this.resetForm("form");
        },
        sceneCodeFormat (row) {
            return this.selectDictLabel(this.sceneCodeOptions, row.sceneCode);
        },
        userLevelFormat (row) {
            return this.selectDictLabel(this.userLevelOptions, row.userLevel);
        },
        useStatusFormat (row) {
            if (row.useStatus == "T") {
                return "已使用"
            } else {
                return "未使用"
            }
        },
        vipDurationFormat (row) {
            return this.selectDictLabel(this.vipDurationOptions, row.vipDuration);
        },

        /** 搜索按钮操作 */
        handleQuery () {
            this.queryParams.pageIndex = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery () {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 新增按钮操作 */
        handleAdd () {
            this.reset();
            this.open = true;
            this.title = "添加激活券发放记录表";
            this.isEdit = false;
        },
        // 多选框选中数据
        handleSelectionChange (selection) {
            this.ids = selection.map((item) => item.couponUserId);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 修改按钮操作 */
        handleUpdate (row) {
            this.reset();
            const couponUserId = row.couponUserId || this.ids;
            getActivationCouponUser(couponUserId).then((response) => {
                this.form = response.data;
                this.open = true;
                this.title = "修改激活券发放记录表";
                this.isEdit = true;
            });
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    if (this.form.couponUserId !== undefined) {
                        updateActivationCouponUser(this.form).then((response) => {
                            if (response.code === 200) {
                                this.msgSuccess("修改成功");
                                this.open = false;
                                this.getList();
                            } else {
                                this.msgError(response.msg);
                            }
                        });
                    } else {
                        addActivationCouponUser(this.form).then((response) => {
                            if (response.code === 200) {
                                this.msgSuccess("新增成功");
                                this.open = false;
                                this.getList();
                            } else {
                                this.msgError(response.msg);
                            }
                        });
                    }
                }
            });
        },
        // 核销
        handlePut (row) {
            // console.log(row)
            this.$confirm('是否对核销该笔订单', '系统提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                putUseOrder(row.orderId, {
                    orderId: row.orderId,
                    usedAt: this.formatDate(new Date())
                }).then(res => {
                    this.$message.success(res.msg);
                })
            })
        },
        formatDate (time) {
            let date = new Date(time).valueOf();
            let now = new Date();
            let year = new Date(time).getFullYear().toString().padStart(2, '0');
            let mon = (new Date(time).getMonth() + 1).toString().padStart(2, '0');
            let timeDate = new Date(time).getDate()
            let day = timeDate.toString().padStart(2, '0');
            let h = new Date(time).getHours().toString().padStart(2, '0');
            let m = new Date(time).getMinutes().toString().padStart(2, '0');
            let s = new Date(time).getSeconds().toString().padStart(2, '0');
            return `${year}-${mon}-${day} ${h}:${m}:${s}`
        },
        /** 删除按钮操作 */
        handleDelete (row) {
            if (row.tradeStatus != 'created') {
                this.$message.error('未付款的订单才可以取消')
                return false
            }
            const Ids = row.orderId || this.ids;
            this.$confirm('是否确认删除编号为"' + Ids + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(function () {
                    return delEduOrder(Ids);
                })
                .then(() => {
                    this.getList();
                    this.msgSuccess("删除成功");
                })
                .catch(function () { });
        },
    },
};
</script>
